<?php

namespace app\api\controller;

use app\admin\controller\UserTask;
use app\api\BaseApi;
use app\model\ModelCaptcha; //验证码实体
use app\model\ModelUser;
use app\model\ModelUserLoginLog;
use app\model\ModelUserTask;
use app\Request;
use app\service\TaskService;
use app\service\UserAccountService;
use app\service\UserService;
use think\response\Json;

/**
 * Class User
 * @package app\api\controller
 */
class User extends BaseApi
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     *新增用户
     * edit by jack 2021-03-28
     */
    public function createUser(): Json
    {
        $mobile = trim(input('mobile')); //手机号
        if (empty($mobile)) {
            return $this->error('手机号不可为空', '', '100105-01');
        }
        $res = $this->isMobile($mobile);
        if (!$res) {
            return $this->error('请输入正确的手机号码', '', '100105-02');
        }
        $captcha = trim(input('captcha')); //验证码
        $captchaId = trim(input('captchaId')); //验证码后端ID
        if (empty($captcha) || empty($captchaId)) {
            return $this->error('验证码不可为空', '', '100105-03');
        }
        $equipment_name = trim(input('equipment_name'));
        if (empty($equipment_name)) {
            return $this->error('设备名称为空', '', '100105-04');
        }
        $login_ip = trim(input('ip'));
        if (empty($login_ip)) {
            return $this->error('登录IP为空', '', '100105-05');
        }
        //验证验证码是否有效
        $isCaptcha = $this->checkCaptchaCode($mobile, $captcha, $captchaId);
        if (!$isCaptcha) {
            return $this->error('无效验证码', '', '100105-06');
        }
        $pwd = trim(input('pwd')); //密码
        if (empty($pwd)) {
            return $this->error('密码不可为空', '', '100105-07');
        }
        $realName = trim(input('realName')); //真实名称
        if (empty($realName)) {
            return $this->error('真实名称不可为空', '', '100105-08');
        }
        $userModel = new ModelUser();
        $invitationCode = trim(input('invitationCode'));  //谁邀请这个用户来注册的邀请码
        $pid = 0;
        $lv_path = '';
        if (!empty($invitationCode)) {
            $pWhere = [
                'my_invitation_code' => $invitationCode
            ];
            $p_user = $userModel->where($pWhere)->findOrEmpty() -> toArray();
            if ($p_user) {
                $pid = $p_user['id'];
                $lv_path = $p_user['lv_path'];
            } else {
                //邀请码错误
              return  $this->error('您输入的邀请码错误，请确认后重试', '', '100105-09');
            }
        }else{
            return  $this->error('请输入邀请码', '', '100105-09-10');
        }
        if(empty($pid)){
            return  $this->error('关系错误：'.$invitationCode, '', '100105-09-11');
        }
        if (empty($lv_path)) {
            $lv_path = $pid;
        } else {
            $lv_path = $lv_path . '-' . $pid;
        }
        if(empty($lv_path)){
            return  $this->error('路径错误', '', '100105-09-10');
        }
        $userService = new UserService();
        $data = [
            'pid' => $pid,
            'lv_path' => $lv_path,
            'vip_lv' => 0,
            'real_name' => $realName,
            'password' => md5($pwd),
            'mobile' => $mobile,
            'equipment_name' => $equipment_name,
            'invitation_code' => $invitationCode,
            'invitation_user_id' => $pid,
            'login_ip' => $login_ip
        ];
        $result = $userService->createUser($data);
        if($result['status'] == 0){
            //创建失败
            return $this->error($result['msg'],'','100105-40');
        }else{
            return $this->success($result['msg'],$result['data']);
        }
    }

    /**
     * 检查验证码的有效性
     * add by jack 2021-03-28
     * @param string $mobile 用户手机号
     * @param string $captcha 验证码
     * @param string $captchaId 服务端端下发的验证码唯一ID
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function checkCaptchaCode(string $mobile, string $captcha, string $captchaId)
    {
        $modelCaptcha = new ModelCaptcha();
        $where = [
            'mobile' => $mobile,
            'captcha' => $captcha,
            'id' => $captchaId,
        ];
        $result = $modelCaptcha->where($where)->count();
        return $result > 0;
    }

    /**
     * 找回密码
     */
    public function forgetPWD(): Json
    {
        $mobile = trim(input('mobile')); //手机号
        if (empty($mobile)) {
            return $this->error('手机号不可为空', '', '100105-10');
        }
        $res = $this->isMobile($mobile);
        if (!$res) {
            return $this->error('请输入正确的手机号码', '', '100105-11');
        }
        $equipment_name = trim(input('equipment_name'));
        if (empty($equipment_name)) {
            return $this->error('设备名称为空', '', '100105-12');
        }
        $login_ip = trim(input('ip'));
        if (empty($login_ip)) {
            return $this->error('登录IP为空', '', '100105-13');
        }
        $captcha = trim(input('captcha')); //验证码
        $captchaId = trim(input('captchaId')); //验证码后端ID
        if (empty($captcha) || empty($captchaId)) {
            return $this->error('验证码不可为空', '', '100105-14');
        }
        $pwd = trim(input('pwd')); //密码
        if (empty($pwd)) {
            return $this->error('新密码不可为空', '', '100105-15');
        }
        //验证验证码是否有效
        $isCaptcha = $this->checkCaptchaCode($mobile, $captcha, $captchaId);
        if (!$isCaptcha) {
            return $this->error('验证码无效', '', '100105-16');
        }
        $userService = new UserService();
        $pwd = md5($pwd);
        $resultInfo = $userService->resetPwdByMobile($mobile, $pwd,$login_ip,$equipment_name,$captcha,$captchaId);
        if ($resultInfo['status'] == 1) {
            return $this->success($resultInfo['msg'],$resultInfo['data']);
        } else {
            return $this->error($resultInfo['msg'], '', '100105-17');
        }
    }

    /**
     * 团队及收益：
     * 一级 二级 三级 团队人数
     * 一级 二级 三级 收益
     */
    public function teamShouYi(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userSon = $userService->countUserSon($userInfo['data']['id']);
        $userSonTuiGuangIncome = $userService->countUserSonTuiGuangIncome($userInfo['data']['id']);
        $resul = [
            'userSon' => $userSon['data'],
            'userSonTuiGuangIncome' => $userSonTuiGuangIncome['data']
        ];
        return $this->success('成功', $resul);
    }


    /**
     * 徒弟信息
     * 入参 注册时间
     * 返回数据 当前用户的下一级用户详情 及 下一级用户 拥有下三级用户
     */
    public function getUserTuDi(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $time = trim(input('time'));
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $time = strtotime($time);
        $userSonList = $userService->getUserSonList($userInfo['data']['id'], $time);
        if ($userSonList['status'] == 1 && !empty($userSonList['data'])) {
            foreach ($userSonList['data'] as &$valueSon) {
                $TotalTuDi = 0; // 总徒弟人数
                $TotalVip = 0; //徒弟里面有多少VIP用户
                $TotalIncome = 0; //子级用户的推广收益
                $userSon = $userService->countUserSon($valueSon['id'], false, $time);
                if (!empty($userSon['data'])) {
                    foreach ($userSon['data'] as $item => $value) {
                        $TotalTuDi += intval($value['count']); //总徒弟人数
                    }
                }
                $userSonVip = $userService->countUserSon($valueSon['id'], true, $time);
                if (!empty($userSonVip['data'])) {
                    foreach ($userSonVip['data'] as $item => $value) {
                        $TotalVip += intval($value['count']); //徒弟里面有多少VIP用户
                    }
                }
                $userSonTuiGuangIncome = $userService->countUserSonTuiGuangIncome($valueSon['id'], $time);
                if (!empty($userSonTuiGuangIncome['data'])) {
                    foreach ($userSonTuiGuangIncome['data'] as $item => $value) {
                        $TotalIncome += intval($value['total_popularize_profit']); //徒弟的收益
                    }
                }
                $valueSon['TotalTuDi'] = $TotalTuDi;
                $valueSon['TotalVip'] = $TotalVip;
                $valueSon['TotalIncome'] = $TotalIncome; //徒弟的收益
            }
        }
        return $this->success('成功', $userSonList['data']);
    }

    /**
     * 头像，昵称，我的邀请码，级别
     * lv 等级 等于0 4； 可领取免费任务
     * 可用余额 今日收益 今日完成数量
     */
    public function myInfo(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $time = trim(input('time'));
        //检查用户是否在线
        $userService = new UserService();
        //$field = 'id,mobile,user_token,head_img_url,my_invitation_code,real_name,vip_lv,lv_path';
        $field = '*'; //查出全部字段
        $userInfo = $userService->getUserInfoByToken($user_token, $field);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userId = $userInfo['data']['id'];
        $mobile_txt = substr_replace($userInfo['data']['mobile'], '****', 3, 4);
        $userInfo['data']['mobile'] = $mobile_txt;
        $userAccount = $userService->getUserAccountInfoByUserID($userId);
        if ($userAccount['status'] == 0) {
            return $this->error($userAccount['msg'], '', '100105-24');
        }
        $vip_lv = $userInfo['data']['vip_lv'];
        //$vip_lv_task = 3;//一般用户默认给三个任务
        $vip_lv_task = $this ->getVipTaskCount($vip_lv);
        $userInfo['data']['vip_lv_task'] = $vip_lv_task;
        $userInfo['data']['balance'] = $userAccount['data']['balance'];   //用户可用余额
        unset($userAccount);
        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        //获取用户当天的收益
        $field = 'sum(account_profit) account_profit';
        $userAccountIncome = $userService->getUserAccountIncomeByUserID($userId, $beginToday, $field);
        if ($userAccountIncome['status'] == 0) {
            return $this->error($userAccountIncome['msg'], '', '100105-25');
        }
        // dump($userAccountIncome['data']);die();
        $account_profit = 0;
        if ($userAccountIncome['data']['account_profit'] > 0) {
            $account_profit = $userAccountIncome['data']['account_profit'];
        }
        //用户今日收益
        $userInfo['data']['account_profit'] = $account_profit;
        $userTaskService = new TaskService();
        $userTodayTask = $userTaskService->countUserTodayTaskByUserId($userId);
        //用户今日已领取任务的数量
        $userTodayTaskCount = 0;
        if (!empty($userTodayTask['data'])) {
            $userTodayTaskCount = $userTodayTask['data'];
        }
        $userInfo['data']['userTodayTaskCount'] = $userTodayTaskCount;
        return $this->success('成功', $userInfo['data']);
    }

    /**
     * 编辑用户基本信息
     * @return Json
     */
    public function editUserInfoByToken() : Json
    {
        $user_token = trim(input('user_token'));
        $equipment_name = trim(input('equipment_name'));
        $login_ip = trim(input('ip'));
        if (empty($user_token) || empty($equipment_name) || empty($login_ip)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        //$field = 'id,mobile,user_token,head_img_url,my_invitation_code,real_name,vip_lv,lv_path';
        $field = '*'; //查出全部字段
        $userInfo = $userService->getUserInfoByToken($user_token, $field);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $user_id = $userInfo['data']['id'];
        $head_img = trim(input('head_img')); //头像
        $filename_url = '';
        if(!empty($head_img)){
            $arr = preg_split("/(,|;)/",$head_img);//分隔三部分，data:image/png  base64  后面一堆
            $base64Data = $arr[2];
            $arr2 = explode('/',$arr[0]);      //分割出图片格式
            $file_type = $arr2[1];
            //var_dump($img);
            $file_path = $_SERVER['DOCUMENT_ROOT'].'/upload/'.date("Ymd").'/'.$user_id;
            $dir = iconv("UTF-8", "GBK",$file_path);
            if (!file_exists($dir)) {
                $r =  mkdir($file_path, 0777, true);
                //创建时间文件夹
                if(!$r){
                    return $this->error('创建文件夹失败','', '100104-18');
                }
            }
            $img_name = $this -> getFileName();
            $filename_url = '/upload/'.date("Ymd").'/'.$user_id.'/'.$img_name.'.'.$file_type;
            $filename = $file_path.'/'.$img_name.'.'.$file_type;
            //转码，把utf-8转成gb2312,返回转换后的字符串， 或者在失败时返回 FALSE。
            $filename = iconv("UTF-8","gb2312",$filename);
            //var_dump($filename);die();
            //检查文件是否存在
            if(file_exists($filename)) {
                return $this->error('已存在同名文件请重新上传','', '100105-18-01');
            }
            $img = base64_decode($base64Data);
            $upload_result = file_put_contents($filename, $img);//返回的是字节数
        }
        $head_img = $filename_url;
        $nick_name = trim(input('nick_name')); //昵称
        $sex = trim(input('sex')); //性别
        if (!empty($sex)) {
            if ($sex != '男' && $sex != '女') {
                return $this->error('性别信息错误', '', '100105-41');
            }
        }
        $address = trim(input('address')); //地址
        $mobile = trim(input('mobile')); //手机
        $captcha = '';
        $captchaId = 0;
        if (!empty($mobile)) {
            $res = $this->isMobile($mobile);
            if (!$res) {
                return $this->error('请输入正确的手机号码', '', '100105-42');
            }
            $captcha = trim(input('captcha')); //验证码
            $captchaId = trim(input('captchaId')); //验证码后端ID
            if (empty($captcha) || empty($captchaId)) {
                return $this->error('验证码不可为空', '', '100105-43');
            }
            //验证验证码是否有效
            $isCaptcha = $this->checkCaptchaCode($mobile, $captcha, $captchaId);
            if (!$isCaptcha) {
                return $this->error('无效验证码', '', '100105-44');
            }
        }
        $old_pwd = trim(input('old_pwd')); //旧密码
        $pwd = trim(input('pwd')); //密码
        if (!empty($pwd)) {
            if (empty($old_pwd)) {
                return $this->error('原密码不可为空', '', '100105-45');
            }
        }
        //组装数据
        $data = [
            'equipment_name' => $equipment_name,
            'ip' => $login_ip,
            'head_img' => $head_img,
            'nick_name' => $nick_name,
            'sex' => $sex,
            'address' => $address,
            'mobile' => $mobile,
            'captcha' => $captcha,
            'captchaId' => $captchaId,
            'pwd' => $pwd,
            'old_pwd' => $old_pwd
        ];
        $userService = new UserService();
        $result = $userService->editUserInfoById($user_id, $data);
        if ($result['status'] == 0) {
            return $this->error($result['msg'], '', '100105-46');
        } else {
            return $this->success($result['msg']);
        }
    }

    /**
     * 插入用户收款信息
     * @return Json
     */
    public function insertUserAccountCard() : Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        //$field = 'id,mobile,user_token,head_img_url,my_invitation_code,real_name,vip_lv,lv_path';
        $field = '*'; //查出全部字段
        $userInfo = $userService->getUserInfoByToken($user_token, $field);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userId = $userInfo['data']['id'];
        $income_account = trim(input('income_account'));
        $income_account_name = trim(input('income_account_name'));
        $income_account_code = trim(input('income_account_code')); //收款码文件流
        //$file_type = trim(input('file_type'));
        $filename_url = '';
        if(!empty($income_account_code)){
            /*
            if(empty($file_type)){
                $file_type = 'jpg';
            }
            */

            //$base64 =  trim(input('base_pic')); //图片
            //$img = base64_decode($income_account_code);
            $arr = preg_split("/(,|;)/",$income_account_code);//分隔三部分，data:image/png  base64  后面一堆
            $base64Data = $arr[2];
            $arr2 = explode('/',$arr[0]);      //分割出图片格式
            $file_type = $arr2[1];
            //var_dump($img);
            $file_path = $_SERVER['DOCUMENT_ROOT'].'/upload/'.date("Ymd").'/'.$userId;
            $dir = iconv("UTF-8", "GBK",$file_path);
            if (!file_exists($dir)) {
                $r =  mkdir($file_path, 0777, true);
                //创建时间文件夹
                if(!$r){
                    return $this->error('创建文件夹失败','', '100104-18');
                }
            }
            $img_name = $this -> getFileName();
            $filename_url = '/upload/'.date("Ymd").'/'.$userId.'/'.$img_name.'.'.$file_type;
            $filename = $file_path.'/'.$img_name.'.'.$file_type;
            //转码，把utf-8转成gb2312,返回转换后的字符串， 或者在失败时返回 FALSE。
            $filename = iconv("UTF-8","gb2312",$filename);
            //var_dump($filename);die();
            //检查文件是否存在
            if(file_exists($filename)) {
                return $this->error('已存在同名文件请重新上传','', '100105-18-01');
            }
            $img = base64_decode($base64Data);
            $upload_result = file_put_contents($filename, $img);//返回的是字节数
        }
        $income_account_code_url = $filename_url;
        $income_account_type = trim(input('income_account_type'));
        $income_account_bank_name = trim(input('income_account_bank_name'));
        $income_account_bank_account_name= trim(input('income_account_bank_account_name'));
        $is_default = trim(input('is_default'));
        if (empty($income_account) || empty($income_account_name) || empty($income_account_type)) {
            return $this->error('参数错误', '', '100105-28');
        }
        if ($income_account_type != 101 && $income_account_type != 201 && $income_account_type != 301) {
            return $this->error('收款类型错误', '', '100105-29');
        }
        if($income_account_type == 101){
            if(empty($income_account_bank_name) || empty($income_account_bank_account_name)){
                return $this->error('收款银行和支行名称不可为空', '', '100105-29-01');
            }
        }
        if($income_account_type != 101){
            if(empty($income_account_code_url)){
                return $this->error('请上传收款码图片', '', '100105-29-02');
            }
        }
        if($is_default != 1  && $is_default !=0){
            return $this->error('是否默认卡值错误', '', '100105-30');
        }
        $userAccountService = new UserAccountService();
        $result = $userAccountService->insertUserAccountCard($userId, $income_account, $income_account_name, $income_account_code_url,
            $income_account_type,$income_account_bank_name,$income_account_bank_account_name,$is_default);
        if ($result['status'] ==1) {
            return $this->success($result['msg'], $result['data']);
        } else {
            return $this->error($result['msg'], '', '100105-31');
        }
    }

    /**
     * 获取用户收款信息--分页列表
     */
    public function getUserAccountCardList(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $page = trim(input('page'));
        $size = trim(input('size'));
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userAccountService = new UserAccountService();
        $result = $userAccountService -> getUserAccountCardList($userInfo['data']['id'],$page,$size);
        if($result['status'] == 0){
            return $this->error($result['msg'], '', '100107-112');
        }else{
            return $this->success($result['msg'], $result['data']);
        }
    }

    /**
     * 获取用户收款信息--某个卡片
     */
    public function getUserCardInfoById(): Json
    {
        $user_token = trim(input('user_token'));
        $id = trim(input('id'));
        if (empty($user_token) || empty($id)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userAccountService = new UserAccountService();
        $result = $userAccountService -> getUserCardInfoById($userInfo['data']['id'],$id);
        if($result['status'] == 0){
            return $this->error($result['msg'], '', '100107-122');
        }else{
            return $this->success($result['msg'], $result['data']);
        }
    }

    /**
     * 删除用户收款信息--某个卡片
     */
    public function deleteUserCardInfoById(): Json
    {
        $user_token = trim(input('user_token'));
        $id = trim(input('id'));
        if (empty($user_token) || empty($id)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userAccountService = new UserAccountService();
        $result = $userAccountService -> deleteUserCardInfoById($userInfo['data']['id'],$id);
        if($result['status'] == 0){
            return $this->error($result['msg'], '', '100107-122');
        }else{
            return $this->success($result['msg'], $result['data']);
        }
    }

    /**
     * 获取用户自己的提现信息--支持动态分页
     */
    public function getUserAccountCostForPage(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $page = trim(input('page'));
        $size = trim(input('size'));
        $time_day = trim(input('time_day'));
        $today = date('Ymd'); //20210424
        if(empty($time_day)){
            $time_day = $today -7; //默认查询最近7天数据
        }
        if($time_day == $today){
            $time_day = $time_day -7;
        }
        //20210424    20210101
        //最大不可以查60天以前的数据
        if(($today - $time_day) > 60 ) {
            $time_day = $today - 60;
        }
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userAccountService = new UserAccountService();
        $result = $userAccountService -> getUserAccountCostForPage($userInfo['data']['id'],$time_day,$page,$size);
        if($result['status'] == 0){
            return $this->error($result['msg'], '', '100107-122');
        }else{
            return $this->success($result['msg'], $result['data']);
        }
    }

    /**
     * 编辑用户收款基本信息--某个卡片
     * @return Json
     */
    public function editUserCardInfoById() : Json
    {
        $user_token = trim(input('user_token'));
        $id = trim(input('id'));
        if (empty($user_token) || empty($id)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        //$field = 'id,mobile,user_token,head_img_url,my_invitation_code,real_name,vip_lv,lv_path';
        $field = '*'; //查出全部字段
        $userInfo = $userService->getUserInfoByToken($user_token, $field);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userId = $userInfo['data']['id'];
        $income_account = trim(input('income_account'));
        $income_account_name = trim(input('income_account_name'));
        $income_account_code = trim(input('income_account_code'));
        $filename_url = '';
        if(!empty($income_account_code)){
            $arr = preg_split("/(,|;)/",$income_account_code);//分隔三部分，data:image/png  base64  后面一堆
            $base64Data = $arr[2];
            $arr2 = explode('/',$arr[0]);      //分割出图片格式
            $file_type = $arr2[1];
            //var_dump($img);
            $file_path = $_SERVER['DOCUMENT_ROOT'].'/upload/'.date("Ymd").'/'.$userId;
            $dir = iconv("UTF-8", "GBK",$file_path);
            if (!file_exists($dir)) {
                $r =  mkdir($file_path, 0777, true);
                //创建时间文件夹
                if(!$r){
                    return $this->error('创建文件夹失败','', '100104-18');
                }
            }
            $img_name = $this -> getFileName();
            $filename_url = '/upload/'.date("Ymd").'/'.$userId.'/'.$img_name.'.'.$file_type;
            $filename = $file_path.'/'.$img_name.'.'.$file_type;
            //转码，把utf-8转成gb2312,返回转换后的字符串， 或者在失败时返回 FALSE。
            $filename = iconv("UTF-8","gb2312",$filename);
            //var_dump($filename);die();
            //检查文件是否存在
            if(file_exists($filename)) {
                return $this->error('已存在同名文件请重新上传','', '100105-18-01');
            }
            $img = base64_decode($base64Data);
            $upload_result = file_put_contents($filename, $img);//返回的是字节数
        }
        $income_account_code_url = $filename_url;
        $income_account_type = trim(input('income_account_type'));
        $income_account_bank_name = trim(input('income_account_bank_name'));
        $income_account_bank_account_name = trim(input('income_account_bank_account_name'));
        $is_default = trim(input('is_default'));
        if (empty($income_account) || empty($income_account_name) || empty($income_account_type)) {
            return $this->error('参数错误', '', '100105-72');
        }
        if ($income_account_type != 101 && $income_account_type != 201 && $income_account_type != 301) {
            return $this->error('收款类型错误', '', '100105-73');
        }
        if($income_account_type == 101){
            if(empty($income_account_bank_name) || empty($income_account_bank_account_name)){
                return $this->error('收款银行和支行名称不可为空', '', '100105-29-01');
            }
        }
        if($is_default != 1  && $is_default !=0){
            return $this->error('是否默认卡值错误', '', '100105-74');
        }
        $userAccountService = new UserAccountService();
        $result = $userAccountService->editUserCardInfoById($userId,$id, $income_account, $income_account_name, $income_account_code_url,
            $income_account_type,$income_account_bank_name,$income_account_bank_account_name,$is_default);
        if ($result['status'] ==1) {
            return $this->success($result['msg'], $result['data']);
        } else {
            return $this->error($result['msg'], '', '100105-75');
        }
    }


    /**
     * 获取用户自己的收益信息--支持动态分页，支持按日期查：20210415
     */
    public function getUserAccountIncomeForPage(): Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        $income_time_day = trim(input('time_day'));
        $today = date('Ymd'); //20210424
        if(empty($income_time_day)){
            $income_time_day = $today -7; //默认查询最近7天数据
        }
        if($income_time_day == $today){
            $income_time_day = $income_time_day -7;
        }
        //20210424    20210101
        //最大不可以查60天以前的数据
        if(($today - $income_time_day) > 60 ) {
            $income_time_day = $today - 60;
        }
        $page = trim(input('page'));
        $size = trim(input('size'));
        //检查用户是否在线
        $userService = new UserService();
        $userInfo = $userService->checkUerIsOnlineByToken($user_token);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userAccountService = new UserAccountService();
        $result = $userAccountService -> getUserAccountIncomeForPage($userInfo['data']['id'],$income_time_day,$page,$size);
        if($result['status'] == 0){
            return $this->error($result['msg'], '', '100107-132');
        }else{
            return $this->success($result['msg'], $result['data']);
        }
    }

    /**
     * 重置手机号码
     * @return Json
     */
    public function resetMobile() : Json
    {
        $user_token = trim(input('user_token'));
        if (empty($user_token)) {
            return $this->error('非法访问', '', $this::ERROR_CODE);
        }
        //检查用户是否在线
        $userService = new UserService();
        //$field = 'id,mobile,user_token,head_img_url,my_invitation_code,real_name,vip_lv,lv_path';
        $field = '*'; //查出全部字段
        $userInfo = $userService->getUserInfoByToken($user_token, $field);
        if ($userInfo['status'] == 0) {
            return $this->error($userInfo['msg'], '', $userInfo['data']);
        }
        $userId = $userInfo['data']['id'];
        $mobile = trim(input('mobile'));
        $captcha = trim(input('captcha'));
        $captchaId = trim(input('captchaId'));
        $mobile_old = trim(input('mobile_old'));
        $captcha_old = trim(input('captcha_old'));
        $captchaId_old = trim(input('captchaId_old'));
        $ip = trim(input('ip'));
        $equipment_name = trim(input('equipment_name'));
        if (empty($mobile) || empty($captcha) || empty($captchaId)
            || empty($mobile_old) || empty($captcha_old)  || empty($captchaId_old) || empty($ip) || empty($equipment_name)
         ) {
            return $this->error('参数错误', '', '100105-142');
        }
        //验证验证码是否有效--原手机验证码
        $isCaptcha = $this->checkCaptchaCode($mobile, $captcha, $captchaId);
        if (!$isCaptcha) {
            return $this->error('原手机验证码无效', '', '100105-143');
        }
        //验证验证码是否有效--新手机验证码
        $isCaptcha = $this->checkCaptchaCode($mobile_old, $captcha_old, $captchaId_old);
        if (!$isCaptcha) {
            return $this->error('新手机验证码无效', '', '100105-144');
        }
        $userService = new UserService();
        $result = $userService -> resetMobile($userId,$mobile_old,$mobile,$ip,$equipment_name);
        if($result['status'] == 0){
            return $this->error($result['msg'], '', '100105-145');
        }else{
            return $this->success($result['msg'], $result['data']);
        }
    }




    /**
     * 测试方法
     */
    public function test(){
        die('What are you ding?');
        //$userAccountService = new UserAccountService();
        //$r = $userAccountService -> checkUerRecharge(46,1,2,1,'user_account_recharge');
        //dump($r);
        dump('dddd');
        $task = new TaskService();
        $s = $task -> checkUserCompleteTaskById(82,3,1);
        dump($s);
    }

}